<?php
namespace cms\modules\v1\models\shop;

use api\modules\v1\models\circle\Circle;
use common\models\friend\FriendApply;
use common\models\Functions;
use common\models\shop\Goods;
use common\models\Status;
use common\queue\User;
use yii\base\Exception;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class GoodsComment extends \common\models\shop\GoodsComment
{

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getListData($page = 1, $size = 20) {
        try {
            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件
            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();
            $data = static::setPageinationAPI($page, $size, $count);
            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'create_time ASC';

            $query = static::getObjectByAndWhere($searchWhere['where'],$searchWhere['andWhere'], '*', $orderSql, $offset, $size);
            $data['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     */
    public function getSearch () {
        $where['is_delete'] = Status::COMMON_RADIO_NO;
        $andWhere = [];
        $loginName = Yii::$app->request->get('login_name','');
        $status = Yii::$app->request->get('status','');

        if ($status) {
            $where['status'] = (int) $status;
        }

        if ($loginName) {
            $ids = \common\models\user\User::searchByName($loginName);
            $where['user_id'] = $ids;
        }

        return [
            'where' => $where,
            'andWhere' => $andWhere,
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query = null) {
        if (empty($query)) {
            return null;
        }

        $list = $query->with([
            'user' => function ($q) {
                $q -> select(['id','nick_name','user_face','login_name']);
            },
            'replyUser' => function ($q) {
                $q -> select(['id','nick_name','user_face','login_name']);
            },
            'goods'

        ])->asArray()->all();

        foreach ($list as &$v) {
            $singImUserInfo = ArrayHelper::getValue($v,'user',[]);
            $singUserInfo = ArrayHelper::getValue($singImUserInfo,'user',[]);

            $v['user_face'] = static::getAvatar($singImUserInfo['user_face']);
            $v['time'] = $v['update_time'] ?: $v['create_time'];

            $imageTmp = [];
            $imageArray = $v['goods']['deputy_image'] ? json_decode($v['goods']['deputy_image'],true) : [];
            if ($imageArray) {
                foreach ($imageArray as $vv) {
                    $imageTmp[] = static::getImages($vv);
                }
            }
            $v['deputy'] = $imageTmp ?? '';

        }
        return $list;
    }

    //删除
    public function getDelete()
    {
        try{
            $get = Yii::$app->request->get();
            $id = (int) $get['id'];
            if (empty($id)) {
                throw new Exception("参数有误");
            }

            $commentInfo = static::getOneInfoById($id);
            if (empty($commentInfo)) {
                throw new Exception("未知信息");
            }

            $update['is_delete'] = status::COMMON_STATUS_SHOW;
            $res = static::updateData($update,['id' => $id]);
            if (!$res){
                throw new Exception('删除失败');
            }

            //评论数量
            Circle::updateAllCounters(['comment_num' => -1],['id' => $commentInfo['circle_id']]);

            return Functions::formatRestAPI(0, '删除成功');
        }catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    public function queryAudit() {
        $where['status'] = Status::COMMON_CHECKING_WAITING;
        $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;

        $count = static::getCountByWhere($where);

        return Functions::formatRestAPI(0, '', $count);
    }

    /**
     * 审核
     * @return array
     * @throws \yii\db\Exception
     */
    public function saveExamine() {
        $trans = Yii::$app->db->beginTransaction();
        try{
            $id = Yii::$app->request->post('id','');
            $status = Yii::$app->request->post('status','');
            $reason = Yii::$app->request->post('reason','');
            if (empty($id)|| empty($status)){
                throw new Exception('缺少参数');
            }

            if (!is_array($id)) {
                $ids = [$id];
            } else {
                $ids = $id;
            }

            if($status == Status::COMMON_CHECKING_DEFEAT) {
                if (empty($reason)){
                    throw new Exception('请填写驳回理由');
                }
                $data['reason'] = $reason;
            }

            foreach ($ids as $v) {
                $data['status'] = $status;
                $res = static::updateData($data, ['id' => $v]);
                if ($res === false){
                    throw new Exception('操作失败');
                }
                $info = static::getOneInfoById($v);
                $user = User::getOneInfoById($info['user_id']);

                if($status == Status::COMMON_CHECKING_SUCCESS) {
                    //评论数量
                    Circle::updateAllCounters(['comment_num' => 1],['id' => $info['goods_id']]);

                    if($info['topic_user_id']){
                        //评论数量
                        Goods::updateAllCounters(['comment_nums' => 1],['id' => $id]);

                        // 未读数量
                        (new FriendApply())->notReadApplyNum($data['topic_user_id']);
                    }


                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }



}
